//chatserver.c
//
//	Team 7 
//
//	Server program designed for N-way communication between clients

#include "syscall.h"
#include "stdio.h"
#include "stdlib.h"

#define MAXBUFFERSIZE 100
#define MAXPORT 127

int main(int argc, char** argv){
	int socket_desc;
	//struct sockaddr_in address;
	int port = 15;
	int newSocket;
	int clients[MAXPORT];
	char buffer[1024];    // data buffer of 1K 
	
	int valread;
	int bytesRead;
	char readBuffer[MAXBUFFERSIZE];
        int i;

	 for(i = 0; i< MAXPORT; i++)
		clients[i] = -1;

	printf("Listening on port %d\n",port);
	
	while(1){
		//Try to get new client
		newSocket = accept(port);
		
		if(newSocket > -1){
			printf("Hi, welcome to the chat room, %d.\n\r",newSocket);
			for(i = 0; i< MAXPORT; i++){
				if(clients[i] == -1){
					clients[i] = newSocket;
					break;
				}
			}
		}
		
		//Check to see if any clients said anything
		
		int i;
		for(i=0;i<MAXPORT;i++){
			int socket = clients[i];
			if(socket != -1){
				if ((valread = read(socket, buffer, 1024)) < 0) {
			     		 clients[i] = -1;
				}else{
					buffer[valread] = 0;
				  
					if(valread > 0){
						printf("Broadcasting %s\n",buffer);
					
						//Broadcast
						int j;
						for(j=0;j<MAXPORT;j++){
							if(clients[j] != -1){
								if (write(clients[j],buffer,strlen(buffer)) < 0) {
									clients[j] = -1;
								}
							}
						}
					}
				}		
			}
		}
				
		
	}
	
	return 0;	
}
